package com.baymax.test.scene

import android.content.Context
import android.widget.FrameLayout
import androidx.media3.common.MediaItem
import androidx.media3.common.Player
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.ui.PlayerView
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope

/**
 * @title:       标题
 * @project:     TestScene
 * @package:     com.baymax.test.scene
 * @class:       Player
 * @description:
 * <p>
 * 类描述
 * </p>
 *
 * @version:   1.0
 * @createDate:   2023/4/27 14:33
 * @Copyright (C) 2023 YSTEN
 * @author:       xuyujian
 */
class ExoPlayer(context: Context) : FrameLayout(context), CoroutineScope by MainScope(),
    Player.Listener {


    private val surfaceView: PlayerView = PlayerView(context)

    fun start(source: String) {
        startInternal {
            setMediaItem(MediaItem.fromUri(source))
        }
    }

   private fun startInternal(action: ExoPlayer.() -> Unit = {} ) {
        if (surfaceView.parent == null) {
            addView(surfaceView, FrameLayout.LayoutParams(-1, -1))
        }
        stop()
        val player = ExoPlayer.Builder(context).build()
        player.repeatMode = ExoPlayer.REPEAT_MODE_ALL
        player.addListener(this)
        action(player)



        player.prepare()
        player.play()
        surfaceView.player = player
    }

    fun stop() {
        kotlin.runCatching {
            surfaceView.player?.stop()
            surfaceView.player?.release()
        }
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        stop()
    }

}